package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.R;
import com.itheima.mapper.EmployeeMapper;
import com.itheima.pojo.Employee;
import com.itheima.service.EmployeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public R login(Employee employee) {
        //  判断传来的 employee  是否为空
        if (employee == null) {
            return R.error("参数为空");
        }
        //  将从前端获得的密码 转成md5格式
        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        //  根据  username 查询 库 内的employee 是否存在
        LambdaQueryWrapper<Employee> wap = new LambdaQueryWrapper<>();
        wap.eq(Employee::getUsername, employee.getUsername());
        //  Employee one = employeeMapper.selectOne(wap);
        Employee selectEmployee = this.getOne(wap);
        if (selectEmployee == null) {
            return R.error("该用户不存在");
        }
        //  判断库里的 md5 加密密码和 md5转换后的输入的密码  是否一致
        if (!selectEmployee.getPassword().equals(password)) {
            return R.error("密码错误");
        }
        //  判断员工状态是否被禁用
        if (selectEmployee.getStatus() != 1) {
            return R.error("员工账号被禁用");
        }
        //  返回成功
        return R.success(selectEmployee);
    }

    @Override
    public R findPage(Integer page, Integer pageSize, String name) {
        IPage<Employee> p = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> wrap = new LambdaQueryWrapper<>();
        if (null != name) {
            wrap.like(Employee::getName, name);
        }
        IPage<Employee> selectPage = this.page(p, wrap);
        return R.success(selectPage);
    }

    @Override
    public R updateStatus(Employee employee) {
        if (employee == null) {
            return R.error("非法参数");
        }
        Employee byId = this.getById(employee);
        if (byId == null) {
            return R.error("该用户不存在");
        }
        employeeMapper.updateById(employee);
        return R.success("修改成功");
    }
}
